package com.ayitubie.refuelweb.config.sftp;

import com.jcraft.jsch.*;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.Properties;


@Configuration
public class sftpConnectConfig {
    @Value("${sftp.username}")
    private String username;
    @Value("${sftp.password}")
    private String password;
    @Value("${sftp.host}")
    private String host;
    @Value("${sftp.port}")
    private String port;

    private Session getSession() throws JSchException {
        JSch jSch = new JSch();
        int servPort = Integer.parseInt(port.trim());
        Session session = jSch.getSession(username, host, servPort);
        if (password != null) {
            session.setPassword(password);
        }
        Properties config = new Properties();
        config.put("StrictHostKeyChecking", "no");
        session.setTimeout(60*1000);
        session.setConfig(config);
        session.connect();
        return session;
    }

    @Bean
    public ChannelSftp channelSftp() {
        ChannelSftp sftp = null;
        try {
            Session session = getSession();
            Channel channel = session.openChannel("sftp");
            channel.connect();
            sftp = (ChannelSftp) channel;
        } catch (JSchException e) {
            e.printStackTrace();
            System.out.println("初始化链接Bean连接失败");
        }
        return sftp;
    }

    @Bean
    public ChannelExec channelExec() {
        ChannelExec sftp = null;
        try {
            Session session = getSession();
            Channel channel = null;
            channel = session.openChannel("exec");
            channel.connect();
            sftp = (ChannelExec) channel;
        } catch (JSchException e) {
            System.out.println("连接失败");
        }
        return sftp;
    }

}
